import { CART_DATA, CART_INCR, CART_DECR, CART_DEL } from '../types'

export default {
    // 总数据
    [CART_DATA.slice(5)](state, data) {
        let isTrue = state.cartData.some(item => {
            if (item.gid === data.gid) { // gid相同，num++
                console.log(item.num)
                item.num++
                localStorage.setItem("cart", JSON.stringify(state.cartData));
                // console.log('gid相同，num++')
            }
            return item.gid === data.gid
        })
        if (!isTrue) { // gid不同 直接插入
            state.cartData.push({ ...data, checked: true, num: 1 })
            localStorage.setItem("cart", JSON.stringify(state.cartData));
            // console.log('gid不同 直接插入')
        }
    },
    // 按钮++
    [CART_INCR.slice(5)](state, index) {
        state.cartData[index].num++
        localStorage.setItem("cart", JSON.stringify(state.cartData));
    },
    // 按钮--
    [CART_DECR.slice(5)](state, index) {
        if (state.cartData[index].num > 1) {
            state.cartData[index].num--
            localStorage.setItem("cart", JSON.stringify(state.cartData));
        } else {
            state.cartData.splice(index, 1)
            localStorage.setItem("cart", JSON.stringify(state.cartData));
        }
    },
    // 删除按钮
    [CART_DEL.slice(5)](state, index) {
        state.cartData.splice(index, 1)
        localStorage.setItem("cart", JSON.stringify(state.cartData));
    },
    // 改变state
    changeState(state, data) {
        state.cartData = data
        localStorage.setItem("cart", JSON.stringify(state.cartData))
    }
}